# coding=utf-8

from Game21 import Game21


# 处理聊天室相关命令，如加入、移除、聊天、参与游戏等
class ChatRoom:

    def __init__(self, name):
        self.name = name
        self.sessions = []
        self.game = Game21()

    def get_name(self):
        return self.name

    # 用户进入房间
    def add(self, session):
        line = str(session.get_name()) + " has entered the room."
        self._broadcast(line)
        self.sessions.append(session)

    # 用户离开房间，房间的删除在外部处理
    def remove(self, session):
        self.sessions.remove(session)
        line = str(session.get_name()) + " has left the room."
        self._broadcast(line)
        return len(self.sessions)

    # 房间内聊天
    def chat(self, speaker, message):
        message = str(speaker.get_name()) + ": " + message
        self._broadcast(message)

    # 查询房间内用户
    def look(self, speaker):
        line = "The following are in this room:"
        speaker.send(line)
        for session in self.sessions:
            line = str(session.get_name())
            speaker.send(line)

    # 房间内广播，给消息加上一个头
    def _broadcast(self, message):
        message = "[%s] %s" % (self.name, message)
        for session in self.sessions:
            session.send(message)

    # 参与游戏
    def play_game(self, player, expression):
        try:
            score, winner, is_end, is_better, is_played = self.game.play_game(player.get_name(), expression)
        except Exception, e:
            player.send(str(e))
        else:
            # 只要输入合法就返回分数
            player.send("Your score is %d." % score)
            if is_played:
                player.send("You have already played.")
            elif is_end:
                self.end_game()
            elif is_better:
                self._broadcast("Current winner is %s, score = %d, time = %d sec." % winner)
            else:
                pass

    # 开始游戏
    def begin_game(self):
        self._broadcast("New 21 game start.")
        self.game.begin()
        # 四个数字是在调用problem()函数时产生，不要多次调用
        message = str(self.game.problem())[1:-1]
        self._broadcast(message)

    # 结束游戏
    def end_game(self):
        if self.game.is_begin:
            self._broadcast("21 game end.")
            winner = self.game.get_winner()
            if winner[0]:
                self._broadcast("Winner is %s, score = %d, time = %d sec." % winner)
            else:
                self._broadcast("There is no winner.")
            # 该函数一定要在最后调用
            self.game.end()
